package com.letoken.platform.repo.app.redis;

import com.letoken.platform.pub.constant.RedisKeyConstant;
import com.letoken.platform.pub.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @author： letokenlabs
 * @date： 2021/11/24 9:55
 * 登录次数
 */
@Slf4j
public class AdminLoginLimitRedis {
    private StringRedisTemplate stringRedisTemplate;
    private final HashOperations<String, Object, Object> valueOps;

    private AdminLoginLimitRedis() {
        stringRedisTemplate = BeanUtil.getBean(StringRedisTemplate.class);
        this.valueOps = stringRedisTemplate.opsForHash();
    }

    private enum Singleton {
        INSTANCE;
        private AdminLoginLimitRedis instance;

        // JVM会保证此方法绝对只调用一次
        Singleton() {
            instance = new AdminLoginLimitRedis();
        }
    }

    String cacheKey = RedisKeyConstant.ADMIN_LOGIN_LIMIT;

    public static AdminLoginLimitRedis me() {
        return AdminLoginLimitRedis.Singleton.INSTANCE.instance;
    }

    public void incrementCounter(String username) {
        String today = LocalDate.now(ZoneId.of("UTC")).toString();
        String key = cacheKey + today;
        if (!Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            valueOps.increment(key, username, 1L);
            //过期时间3天
            stringRedisTemplate.expire(key, 3, TimeUnit.DAYS);
        } else {
            valueOps.increment(key, username, 1L);
        }

//        if (count != null){
//            if (count > MAX_COUNT) {
//                // 撤销递增的计数
//                valueOps.decrement(key, 1L);
//                throw new RuntimeException("Counter limit exceeded");
//            }
//        }

    }

    public Integer getCount(String username) {
        String today = LocalDate.now(ZoneId.of("UTC")).toString();
        String key = cacheKey + today;
        Object value = valueOps.get(key, username);
        if (value != null) {
            return Integer.valueOf(value.toString());
        }
        return 0;
    }

}
